package main

import (
	"flag"
	"fmt"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"net"
	"os"
	"os/signal"
	"shop_srv/user_srv/internal/global"
	"shop_srv/user_srv/internal/handler"
	"shop_srv/user_srv/internal/initialize"
	"syscall"

	"shop_srv/user_srv/pkg/proto"
)

// GetFreePort 获取动态端口号
func GetFreePort() (int, error) {
	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
	if err != nil {
		return 0, nil
	}
	tcp, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return 0, nil
	}
	defer tcp.Close()
	return tcp.Addr().(*net.TCPAddr).Port, nil
}

// https://github.com/grpc/grpc/blob/master/doc/health-checking.md
func main() {
	port, _ := GetFreePort()
	host := "172.16.30.238"
	IP := flag.String("ip", host, "地址")

	PORT := flag.Int("port", port, "端口号")
	flag.Parse()
	initialize.InitLogger()
	initialize.InitConfig()
	initialize.InitDb()
	zap.S().Info("IP:", *IP)
	zap.S().Info("PORT:", *PORT)
	server := grpc.NewServer()
	proto.RegisterUserServer(server, &handler.UserServer{})
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *IP, *PORT))
	if err != nil {
		panic(err.Error())
	}
	//注册健康检查接口
	grpc_health_v1.RegisterHealthServer(server, health.NewServer())
	//服务注册
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", global.ServerConfig.ConsulConfig.Host, global.ServerConfig.ConsulConfig.Port)
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	//生成对应的检查对象
	check := &api.AgentServiceCheck{
		GRPC:                           fmt.Sprintf("%s:%d", host, port),
		Timeout:                        "5s",
		Interval:                       "5s",
		DeregisterCriticalServiceAfter: "10s",
	}
	agentServiceRegistration := new(api.AgentServiceRegistration)
	agentServiceRegistration.Name = global.ServerConfig.Name
	v6, err := uuid.NewV6()
	agentServiceRegistration.ID = v6.String()
	agentServiceRegistration.Port = *PORT
	agentServiceRegistration.Address = host
	agentServiceRegistration.Tags = []string{"user_srv", "grpc", "user"}
	agentServiceRegistration.Check = check
	err = client.Agent().ServiceRegister(agentServiceRegistration)
	if err != nil {
		panic(err)
	}
	go func() {
		err = server.Serve(listen)
		if err != nil {
			panic(err.Error())
		}
	}()
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err := client.Agent().ServiceDeregister(v6.String()); err != nil {
		zap.S().Error("注销失败")
	}
	zap.S().Error("注销成功")
}
